package com.dk.service.serviceImpl;

import com.dk.jwzx.JwzxHelper;
import com.dk.jwzx.bean.Subject;
import com.dk.service.JwzxService;
import com.dk.util.JsonUtil;
import com.dk.util.ParseUtil;
import com.dk.util.UserLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;

@Service
public class JwzxServiceImpl implements JwzxService {
    private final String SUBJECTS="subjects";
    private final String WEEK="week";

    @Autowired
    private Jedis jedis;

    public int getWeek(){
        int week=JwzxHelper.getWeek();
        if(jedis.exists(WEEK)) {
            if (ParseUtil.stringParseInt(jedis.get(WEEK)) != week) {
                jedis.flushDB();
                jedis.set(WEEK, String.valueOf(week));
            }
        }else jedis.set(WEEK, String.valueOf(week));
        return week;
    }

    public String getSubjects(String stuId)throws Exception{
        if(UserLock.lock(stuId)) {
            if (!jedis.hexists(SUBJECTS, stuId)) {
                Map<Integer, List<Subject>> studentSubjects = JwzxHelper.getStudentSubjects(stuId);
                jedis.hset(SUBJECTS, stuId, JsonUtil.getJsonByObject(studentSubjects));
            }
            String json = jedis.hget(SUBJECTS, stuId);
            UserLock.unlock(stuId);
            return json;
        }else return "";
    }
}
